package com.example.fruitdemo.interceptor;

import org.apache.ibatis.plugin.Interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;


public class LoginInterceptor implements HandlerInterceptor {
  @Autowired
  private StringRedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
     //拿到authorization判断，若有，则放行
        String authorization = request.getHeader("authorization");
        //查询redis中该token剩余时间
        String s = redisTemplate.opsForValue().get(authorization);
        if(s!=null||!s.isEmpty()){
            //查看剩余时间
            Long expire = redisTemplate.getExpire(authorization);
            if(expire<10L){
                //为其刷新时间
                redisTemplate.opsForValue().set(authorization,s, Duration.ofMinutes(30L));
            }
            //放行
            return true;
        }else {
            //没有令牌
            response.getWriter().write("101");
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
